package com.gxa.learning.pc.controller;

import com.github.pagehelper.PageInfo;
import com.gxa.learning.core.common.ExceptionCode;
import com.gxa.learning.core.common.JsonResult;
import com.gxa.learning.core.exception.BusinessException;
import com.gxa.learning.core.pojo.LevelManager;
import com.gxa.learning.core.pojo.TypeLevelManagerVO;
import com.gxa.learning.core.util.ReturnJsonResultUtil;
import com.gxa.learning.pc.service.LevelManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 等级管理的controller
 *
 * @author lijianmin
 * @date 2021/12/02  15:19:41
 */
@RestController
@RequestMapping("/levelMgr")
@Api(tags = "等级管理的接口")
public class LevelManagerController {

    @Resource
    private LevelManagerService levelManagerService;

    /**
     * 删除等级的接口
     *
     * @param map 等级的编号(前端需要使用body接收 所以更改为map)
     * @return 返回是否成功
     */
    @PostMapping("/del")
    @ApiOperation("删除等级的接口")
    @ApiImplicitParam(name = "map", value = "编号", paramType = "body", dataType = "Map")
    public Map<String, Object> del(@RequestBody Map<String, Object> map) throws BusinessException {
        if (map.get("id") == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        }
        Integer integer = levelManagerService.deleteById(Long.parseLong(map.get("id").toString()));
        return ReturnJsonResultUtil.ReturnJsonResultUtil(integer, "删除");
    }

    /**
     * 批量删除等级的接口
     *
     * @param map 等级编号的map集合
     * @return 返回是否成功
     */
    @PostMapping("/batchDel")
    @ApiOperation("批量删除等级的接口")
    @ApiImplicitParam(name = "ids", value = "编号", paramType = "body", dataType = "List")
    public Map<String, Object> batchDel(@RequestBody Map<String, Object> map) throws BusinessException {
        // if (map.get("ids") == null) {
        //     throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        // }

        if (map.isEmpty() || map.get("ids") == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        }
        List<Integer> list = (List<Integer>) map.get("ids");

        List<Long> ids = new ArrayList<>();
        for (Integer integer : list) {
            ids.add(Long.valueOf(integer.toString()));
        }

        //调用批量删除方法
        Boolean integer = levelManagerService.batchDel(ids);
        //给前端返回消息
        return ReturnJsonResultUtil.ReturnJsonResultUtil(integer, "批量删除");
    }

    /**
     * 添加等级的接口
     *
     * @param levelManager 等级对象
     * @return 返回是否成功
     */
    @PostMapping("/add")
    @ApiOperation("添加等级的接口")
    @ApiImplicitParam(name = "levelManager", value = "等级对象", paramType = "body", dataType = "LevelManager", dataTypeClass = LevelManager.class)
    public Map<String, Object> add(@RequestBody LevelManager levelManager) throws BusinessException {
        if (levelManager == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        }
        levelManagerService.selectExist(levelManager);
        LevelManager insert = levelManagerService.insert(levelManager);
        return ReturnJsonResultUtil.ReturnJsonResultUtil(insert, "添加");
    }

    /**
     * 修改等级的接口
     *
     * @param levelManager 等级对象
     * @return 返回是否成功
     */
    @PostMapping("/update")
    @ApiOperation("修改等级的接口")
    @ApiImplicitParam(name = "levelManager", value = "levelManager", paramType = "body", dataType = "LevelManager", dataTypeClass = LevelManager.class)
    public Map<String, Object> update(@RequestBody LevelManager levelManager) throws BusinessException, IllegalAccessException {
        if (levelManager == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        }
        if (levelManager.getId() == null || levelManager.getTypeId() == null || levelManager.getLevel() == null || levelManager.getState() == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_ERROR);
        }
        levelManagerService.selectExist(levelManager);
        Integer integer = levelManagerService.updateById(levelManager);
        return ReturnJsonResultUtil.ReturnJsonResultUtil(integer, "修改");
    }

    /**
     * 批量导入等级的接口
     *
     * @param multipartFile 文件对象
     * @throws Exception 操作中产生的异常
     */
    @PostMapping("/batchAdd")
    @ApiOperation("批量导入等级的接口")
    @ApiImplicitParam(name = "file", value = "上传的文件对象", paramType = "query", dataType = "MultipartFile", dataTypeClass = MultipartFile.class)
    public Map<String, Object> batchAdd(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        //进行参数判断
        if (multipartFile == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        }
        levelManagerService.batchAdd(multipartFile);
        JsonResult jsonResult = new JsonResult();
        // 给json结果集赋值
        jsonResult.setCode("1");
        jsonResult.setMsg("批量导入成功");
        // 通过return返回给前端
        return jsonResult.getDataMap();
    }


    /**
     * 导出等级的方法
     *
     * @param response .
     * @throws Exception .
     */
    @PostMapping("/export")
    @ApiOperation("导出等级的方法")
    @ApiImplicitParam(name = "response", value = "response")
    public void export(@RequestParam(name = "response", required = false) HttpServletResponse response) throws Exception {
        List<LevelManager> all = levelManagerService.selectAll();

        // 工作簿对象(excel文件对象)
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("ETC申请列表");
        String fileName = "ETC申请列表.xls";
        // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = {"编号", "等级", "类别编号", "状态", "上传人编号"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            //先把文字转换为标准的富文本格式
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把转换后的字段名添加到表头行上
            cell.setCellValue(text);
        }
        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 添加数据行:
        int rowNum = 1;
        for (LevelManager item : all) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(item.getId());
            dataRow.createCell(1).setCellValue(item.getLevel());
            dataRow.createCell(2).setCellValue(item.getTypeId());
            dataRow.createCell(3).setCellValue(item.getState());
            dataRow.createCell(4).setCellValue(item.getUploadPeople());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //告诉浏览器, 以附件方式打开,而不是页面上浏览
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    /**
     * 根据条件搜索(如果条件为空 则为全查询, 如果不传分页条件,则默认为第1页10条数据)
     *
     * @param typeName         类别名称
     * @param level            类别等级
     * @param state            每页数据量
     * @param userName 上传人
     * @return 返回数据以及信息
     */
    @GetMapping("/select")
    @ApiOperation("根据条件搜索(如果条件为空 则为全查询, 如果不传分页条件,则默认为第1页10条数据)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "typeName", value = "类别名称", paramType = "query"),
            @ApiImplicitParam(name = "level", value = "类别等级", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "类别状态", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "上传人", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query")
    })
    public Map<String, Object> select(
            @RequestParam(name = "typeName", required = false) String typeName, @RequestParam(name = "level", required = false) String level
            , @RequestParam(name = "state", required = false) Integer state, @RequestParam(name = "userName", required = false) String userName
            , @RequestParam(name = "page", required = false) Integer page, @RequestParam(name = "size", required = false) Integer size) throws BusinessException {
        PageInfo<TypeLevelManagerVO> list = levelManagerService.selectByLike(typeName, level, state, userName, page, size);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("查询成功!");
        jsonResult.setData(list.getList());
        jsonResult.put("count", list.getTotal());
        return jsonResult.getDataMap();
    }

    /**
     * 根据类型ID搜索等级列表
     *
     * @param id 类型编号
     * @return 返回查询到的等级列表
     * @throws IllegalAccessException
     * @throws BusinessException
     */
    @GetMapping("/selectByTypeId")
    @ApiOperation("根据类型ID搜索等级列表")
    @ApiImplicitParam(name = "id", value = "类别编号", paramType = "query")
    public Map<String, Object> selectByTypeId(@RequestParam("id") Long id) throws IllegalAccessException, BusinessException {
        if (id == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        }
        LevelManager levelManager = new LevelManager();
        levelManager.setTypeId(id);
        levelManager.setState(1);
        PageInfo<LevelManager> levelManagerPageInfo = levelManagerService.selectByPageEquals(null, null, levelManager);
        System.out.println(levelManagerPageInfo.getList());
        System.out.println(levelManagerPageInfo.getTotal());
        System.out.println("00000000000000000000000000000000000000000000");
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(levelManagerPageInfo.getList());
        jsonResult.put("count", levelManagerPageInfo.getTotal());
        return jsonResult.getDataMap();


    }

}
